<template>
  <div class="login-container">
    <el-card class="login-card">
      <template #header>
        <h2>登录</h2>
      </template>
      
      <el-form
        :model="form"
        :rules="rules"
        ref="loginForm"
        @submit.prevent="handleLogin"
      >
        <el-form-item prop="username">
          <el-input
            v-model="form.username"
            placeholder="用户名"
            size="large"
            :prefix-icon="User"
          />
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input
            v-model="form.password"
            type="password"
            placeholder="密码"
            size="large"
            :prefix-icon="Lock"
            show-password
          />
        </el-form-item>
        
        <el-form-item>
          <el-button
            type="primary"
            size="large"
            :loading="loading"
            @click="handleLogin"
            style="width: 100%"
          >
            {{ loading ? '登录中...' : '登录' }}
          </el-button>
        </el-form-item>
      </el-form>
      
      <div class="register-link">
        <p>还没有账号？ <a href="#" @click="showRegister = true">立即注册</a></p>
      </div>
    </el-card>

    <!-- 注册对话框 -->
    <el-dialog
      v-model="showRegister"
      title="用户注册"
      width="400px"
    >
      <el-form
        :model="registerForm"
        :rules="registerRules"
        ref="registerFormRef"
      >
        <el-form-item prop="username">
          <el-input v-model="registerForm.username" placeholder="用户名" />
        </el-form-item>
        <el-form-item prop="email">
          <el-input v-model="registerForm.email" placeholder="邮箱" />
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="registerForm.password" type="password" placeholder="密码" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showRegister = false">取消</el-button>
        <el-button type="primary" @click="handleRegister">注册</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '../store/auth'
import { ElMessage } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'
import api from '../services/api'

export default {
  name: 'Login',
  setup() {
    const router = useRouter()
    const authStore = useAuthStore()

    const form = ref({
      username: '',
      password: ''
    })

    const registerForm = ref({
      username: '',
      email: '',
      password: ''
    })

    const rules = {
      username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
      password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
    }

    const registerRules = {
      username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
      email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
      ],
      password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
    }

    const loading = ref(false)
    const showRegister = ref(false)
    const loginForm = ref(null)
    const registerFormRef = ref(null)

    const handleLogin = async () => {
      if (!loginForm.value) return

      try {
        // 验证表单
        await loginForm.value.validate()
        loading.value = true
        
        console.log('开始登录...', form.value.username)
        
        // 调用认证存储的登录方法
        await authStore.login(form.value.username, form.value.password)
        
        console.log('登录成功，准备跳转...')
        console.log('当前认证状态:', authStore.isAuthenticated)
        console.log('当前用户:', authStore.user)
        
        // 显示成功消息
        ElMessage.success('登录成功')
        
        // 添加延迟确保状态更新完成
        setTimeout(() => {
          // 跳转到仪表盘
          console.log('执行跳转到仪表盘')
          router.push('/dashboard')
        }, 100)
        
      } catch (error) {
        console.error('登录失败:', error)
        const message = error.response?.data?.detail || error.message || '登录失败'
        ElMessage.error(message)
      } finally {
        loading.value = false
      }
    }

    const handleRegister = async () => {
      if (!registerFormRef.value) return

      try {
        await registerFormRef.value.validate()
        
        await api.post('/users/', registerForm.value)
        ElMessage.success('注册成功')
        showRegister.value = false
        
        // 自动填充登录表单
        form.value.username = registerForm.value.username
        form.value.password = registerForm.value.password
      } catch (error) {
        console.error('注册失败:', error)
        ElMessage.error('注册失败：' + (error.response?.data?.detail || error.message))
      }
    }

    // 检查是否已经登录，如果已登录则直接跳转
    onMounted(() => {
      console.log('登录页面加载，检查认证状态:', authStore.isAuthenticated)
      if (authStore.isAuthenticated) {
        console.log('用户已登录，自动跳转到仪表盘')
        router.push('/dashboard')
      }
    })

    return {
      form,
      registerForm,
      rules,
      registerRules,
      loading,
      showRegister,
      loginForm,
      registerFormRef,
      handleLogin,
      handleRegister,
      User,
      Lock
    }
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: #f5f5f5;
}

.login-card {
  width: 400px;
}

.register-link {
  text-align: center;
  margin-top: 20px;
}
</style>
